package com.pencilisland.pay.app.mp.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.pencilisland.pay.api.bean.mp.app.MessageRequest;
import com.pencilisland.pay.api.bean.mp.app.MessageResponse;
import com.pencilisland.pay.api.bean.mp.app.VerifySessionREQ;
import com.pencilisland.pay.api.bean.mp.app.VerifySessionRES;
import com.pencilisland.pay.api.bean.wxpay.WxLoginResp;
import com.pencilisland.pay.api.service.CacheService;
import com.pencilisland.pay.app.mp.service.MBService;
/**
* 报文逻辑处理.校验session是否有效
*
* @author breeze
*/
@Service("MB_verifySession")
public class  VerifySessionMB implements MBService {
	Logger log = LoggerFactory.getLogger(getClass());
	@Autowired
	ObjectMapper objectMapper;
	@Autowired
	CacheService cacheService;

	@Override
	public MessageResponse process(MessageRequest request) {
		log.info("校验session[{}]",request.getSessionId());
		
		if(StringUtils.isEmpty(request.getSessionId())){
			return new VerifySessionRES(false,null,"OK");
		}
		
		Object result = cacheService.get(request.getSessionId());
		if(result!=null){
			WxLoginResp resultLogin = (WxLoginResp)result;
			if(!StringUtils.isEmpty(resultLogin.getOpenId())){
				
				return new VerifySessionRES(true,null,"OK");
			}
		}
		
		return new VerifySessionRES(false,null,"OK");
	}
	
	public VerifySessionREQ getRequestBody(MessageRequest request){
		return objectMapper.convertValue(request.getBody(), VerifySessionREQ.class);
	}

}
